// pages/home/home.js
var time_utils = require('../../utils/time_utils')

Page({

  data: {
    images: [
      "cloud://test-qhmap.7465-test-qhmap-1301577769/image/image0_bg.png",
      "cloud://test-qhmap.7465-test-qhmap-1301577769/image/image1_bg.jpg",
      "cloud://test-qhmap.7465-test-qhmap-1301577769/image/image2_bg.jpg",
      "cloud://test-qhmap.7465-test-qhmap-1301577769/image/image3_bg.jpg"
    ],
    testList: [],
    isAdmin: false
  },
  onLoad: function (options) {

  },
  onShow: function () {
    this.getTestData()
  },
  onShareAppMessage: function () {

  },
  //获取考试数据
  getTestData(e) {
    wx.cloud.callFunction({
      name: "database",
      data: {
        action: 'getMyTestData'
      }
    }).then(res => {
      var testList = res.result.testList
      var isAdmin = res.result.isAdmin
      console.log("getMyTestData", testList, comResult)
      //对比当前时间是否过期
      for (let i = 0; i < testList.length; i++) {
        var comResult = time_utils.compareToCurTime(testList[i].deadline)
        var outDate = comResult == -1
        testList[i].outDate = outDate
      }
      this.setData({
        isAdmin: isAdmin,
        testList: testList
      })
    }).catch(err => {
      console.error(err)
    })
  },
  //测试item点击监听
  onTestClick(e) {
    console.log(e)
    var testIndex = e.currentTarget.dataset.index
    var testItem = this.data.testList[testIndex]
    var publishId = testItem.publishId
    if (publishId != null) {
      if (testItem.outDate) {
        // 跳转到答案界面
        wx.navigateTo({
          url: '../test/answer/answer?publishId=' + publishId
        })
      } else {
        //跳转到测试详情界面
        wx.navigateTo({
          url: '../test/detail/detail?publishId=' + publishId
        })
      }
    } else {
      if (testItem.outDate) {
        wx.showToast({
          title: '当前题目已过期',
          icon: 'none'
        })
      } else {
        //跳转到答题信息填写界面
        wx.navigateTo({
          url: '../test/test?testItem=' + encodeURIComponent(JSON.stringify(testItem))
        })
      }
    }
  },
  //考试结果
  onTestAnswerClick(e) {
    console.log(e)
    var testIndex = e.currentTarget.dataset.index
    var testItem = this.data.testList[testIndex]
    wx.navigateTo({
      url: '../test/admin/admin?testItem=' + encodeURIComponent(JSON.stringify(testItem))
    })
  }
})